package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.pojo.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-果蔬浏览接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询果蔬
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询果蔬")
    @CrossOrigin//解决跨域问题
    public Result<List<DishVO>> list(Long categoryId) {
        //1.构建用于获取和设置果蔬信息的key,规则：dish_分类id
        String key = "dish_" + categoryId;
        //2.查看redis缓存中是否有果蔬信息
        /*注意存放进去的是什么数据类型,取出来的时候就是什么数据类型*/
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        //3.如果有缓存,直接返回缓存的果蔬信息
        if (dishVOList != null){
            return Result.success(dishVOList);
        }
        //4.如果没有缓存,查询数据库,并设置缓存
        log.info("根据分类id查询果蔬,categoryId={}", categoryId);
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的果蔬

        dishVOList = dishService.listWithFlavor(dish);
        //5.设置缓存,以List<DishVO>的形式存放,取出来的时候也是List<DishVO>的形式
        redisTemplate.opsForValue().set(key, dishVOList);
        return Result.success(dishVOList);
    }

}
